Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Incrementing a "PlayerID" with a MongoDB Atlas Trigger

I need to have a playerID that is separate from _id and increments with each new entry into my users collection. I have tried to follow this tutorial with no luck. My counter collection is called playerIDCounter and my users collection is simply called users. I want each user document to have a playerID field that increments from 1 onwards.

This is my attempt at adapting the tutorial code for my own purpose:

exports = async function(changeEvent) {
const playerID = changeEvent.fullDocument.playerID;

const playerIDCounter = context.services.get("Cluster0").db(changeEvent.ns.db).collection("playerIDCounter");
const users = context.services.get("Cluster0").db(changeEvent.ns.db).collection(changeEvent.ns.coll);

(db.collection)
const counter = await playerIDCounter.findOneAndUpdate({playerID: changeEvent.ns },{$inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});

const doc = {};

doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value;

const updateRes = await users.updateOne({playerID: playerID},{ $set: doc});

console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result: ${JSON.stringify(updateRes)}`);

}

I also don't know whether or not I already need to have a playerID field in the document before it gets passed to this function. If the playerID field doesn't already exists will it be created and updated automatically? If not, then what placeholder value should playerID have?

I appreciate anyone who takes the time to help me. I have been stuck for a few days and there aren't too many posts on how to increment values in MongoDB.

Edit: I also don't understand the whole doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value bit - what's going on here?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!